package cn.com.joycode.nimble.baidu.bce;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.net.url.UrlQuery;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.HashMap;

@Slf4j
public class BceApi {

    private String apiKey;

    private String secretKey;

    private String accessToken;

    private LocalDateTime lastRefresh = LocalDate.of(2000, 1, 1).atStartOfDay();

    public BceApi(String apiKey, String secretKey) {
        this.apiKey = apiKey;
        this.secretKey = secretKey;
        getToken();
    }

    public boolean getToken() {
        try {
            LocalDateTime currentTime = LocalDateTimeUtil.now();
            long days = LocalDateTimeUtil.between(lastRefresh, currentTime, ChronoUnit.DAYS);
            if (StrUtil.isNotBlank(accessToken) && (days > 10)) {
                return true;
            }
            UrlQuery urlQuery = new UrlQuery();
            urlQuery.add("grant_type", "client_credentials");
            urlQuery.add("client_id", apiKey);
            urlQuery.add("client_secret", secretKey);
            String url = "https://aip.baidubce.com/oauth/2.0/token?".concat(urlQuery.toString());
            String response = HttpUtil.get(url);
            log.info("响应:{}", response);
            JSONObject jsonObject = JSONUtil.parseObj(response);
            accessToken = jsonObject.getStr("access_token");
            log.info("accessToken:{}", accessToken);
            lastRefresh = currentTime;
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public JSONObject licensePlate(String base64Image) {
        try {
            getToken();
            HashMap<String, Object> params = new HashMap<>();
            params.put("image", base64Image);
            String url = "https://aip.baidubce.com/rest/2.0/ocr/v1/license_plate?access_token=".concat(accessToken);
            String response = HttpUtil.post(url, params);
            log.info("接口原始响应:{}", response);
            JSONObject jsonObject = JSONUtil.parseObj(response);
            return jsonObject;
        } catch (Exception e) {
            return null;
        }
    }
}
